import sys
import os

# 获取当前文件所在的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取项目根目录（当前目录的上级目录）
project_root = os.path.dirname(current_dir)
# 将项目根目录添加到Python路径中
sys.path.insert(0, project_root)

"""
应用启动脚本
用于启动FastAPI应用
"""
import uvicorn
import argparse
import socket
import subprocess
import time
from app.utils.config import settings
from app.utils.logger import logger


def is_port_in_use(port: int) -> bool:
    """检查端口是否被占用"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        try:
            s.bind(('0.0.0.0', port))
            return False
        except socket.error:
            return True


def kill_process_on_port(port: int) -> bool:
    """杀死占用特定端口的进程"""
    try:
        if sys.platform.startswith('win'):
            # Windows平台
            result = subprocess.run(
                f'netstat -ano | findstr :{port}',
                shell=True,
                text=True,
                capture_output=True
            )
            if result.stdout:
                # 解析输出，获取PID
                for line in result.stdout.strip().split('\n'):
                    if f':{port}' in line and 'LISTENING' in line:
                        parts = line.strip().split()
                        if len(parts) >= 5:
                            pid = parts[-1]
                            logger.info(f"正在终止进程 PID: {pid}，该进程占用端口: {port}")
                            subprocess.run(f'taskkill /F /PID {pid}', shell=True)
                            return True
            return False
        else:
            # Linux/Mac平台
            result = subprocess.run(
                f"lsof -i :{port} | grep LISTEN",
                shell=True,
                text=True,
                capture_output=True
            )
            if result.stdout:
                for line in result.stdout.strip().split('\n'):
                    parts = line.strip().split()
                    if len(parts) >= 2:
                        pid = parts[1]
                        logger.info(f"正在终止进程 PID: {pid}，该进程占用端口: {port}")
                        subprocess.run(f"kill -9 {pid}", shell=True)
                        return True
            return False
    except Exception as e:
        logger.error(f"终止进程时出错: {e}")
        return False


def check_and_free_port(port: int, auto_kill: bool = True) -> bool:
    """检查并释放端口"""
    if not is_port_in_use(port):
        logger.info(f"端口 {port} 未被占用")
        return True
    
    logger.info(f"端口 {port} 已被占用")
    if auto_kill:
        if kill_process_on_port(port):
            # 等待端口完全释放
            time.sleep(1)
            logger.info(f"已成功释放端口 {port}")
            return True
        else:
            logger.warning(f"无法释放端口 {port}，进程终止失败")
            return False
    return False


def get_server_url():
    """根据环境获取服务器URL"""
    if settings.IS_PRODUCTION:
        return f"http://106.54.165.214:{settings.SERVER_PORT}"
    else:
        return f"http://{settings.SERVER_HOST}:{settings.SERVER_PORT}"


def main():
    """主函数"""
    check_and_free_port(settings.SERVER_PORT)

    # 获取服务器URL
    server_url = get_server_url()
    
    # 打印启动信息
    logger.info("="*50)
    logger.info(f"🚀 启动 TellTech 后端服务")
    logger.info(f"📡 服务器地址: {server_url}")
    logger.info(f"🌍 运行环境: {'开发环境' if settings.IS_DEVELOPMENT else '生产环境'}")
    logger.info(f"🔑 API文档: {server_url}/docs")
    logger.info("="*50)
    
    # 启动服务器
    uvicorn.run(
        "app.main:app",
        host=settings.SERVER_HOST,
        port=settings.SERVER_PORT,
        reload=settings.IS_DEVELOPMENT
    )


if __name__ == "__main__":
    main() 